package info.wangyuan.agent.valid;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Set;

/**
 * 验证名称
 *
 * @author Albert
 * @since 2025-08-16 15:57:56
 */
public class ValidNameValidator implements ConstraintValidator<ValidName, String> {

    private static final Set<String> RESERVED_NAMES = Set.of("null", "undefined", "nan", "true", "false", "select", "drop", "delete", "insert", "update");

    private int min;
    private int max;

    @Override
    public void initialize(ValidName constraintAnnotation) {
        int configuredMin = constraintAnnotation.min();
        int configuredMax = constraintAnnotation.max();

        // 用 Math 处理边界，保证 min ∈ [1, max]，max ∈ [1, 32]（默认值回退）
        this.min = Math.max(1, configuredMin);
        this.max = Math.max(1, configuredMax);

        if (this.min > this.max) {
            this.min = 1;
            this.max = 32;
        }
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return value != null && !value.isBlank() && (value.length() < min || value.length() > max)
                // 只能字母、数字、下划线，且不能以数字开头
                && value.matches("^[a-zA-Z_][a-zA-Z0-9_]*$") && !RESERVED_NAMES.contains(value.toLowerCase());
    }
}
